package com.wangsd.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;


/**
 * 记录日志
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class AspectLogs {
    ThreadLocal<Long> startTime = new ThreadLocal<Long>();


    //申明一个切点 里面是 execution表达式
    @Pointcut("execution(public * com.wangsd.web.*.controller..*.*(..))")
    private void controllerAspect() {
    }

    /**
     * 请求method前打印类容
     *
     * @param joinPoint
     */
    @Before(value = "controllerAspect()")
    public void methodBefore(JoinPoint joinPoint) {

        startTime.set(System.currentTimeMillis());

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        //打印请求内容
        log.debug("请求方法名:{}", joinPoint.getSignature());
        log.debug("请求类方法参数:{}", Arrays.toString(joinPoint.getArgs()));
        //log.debug("请求地址:" + request.getRequestURL().toString());
        //log.debug("请求方式:" + request.getMethod());
        //log.debug("请求类方法:" + joinPoint.getSignature());
        //log.debug("请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
    }

    //在方法执行完结后打印返回内容
    @AfterReturning(returning = "o", pointcut = "controllerAspect()")
    public void methodAfterReturing(JoinPoint joinPoint, Object o) {
//        log.debug("返回方法:{},返回内容:{},花费时间:{}", joinPoint.getSignature(), JSON.toJSON(o), System.currentTimeMillis() - startTime.get());
    }
}
